// 短信默认值配置modal
import React, { useState, useEffect } from "react";
import { Modal, InputNumber, Select, message, Spin } from "antd";
import { addQuotaConfig, quotaConfigHistory } from "../../../services/quotaApi";

const SMSconfigModal = props => {
  const { visible, onCancel, historyData } = props;
  const { quota, quotaType } = historyData || {};
  const [inputValue, updateInputValue] = useState(quota);
  const [selectValue, updateSelectValue] = useState(quotaType);
  const [loading, updateLoading] = useState(false);

  const fetchHistory = async () => {
    updateLoading(true);
    const { errCode, datas } = await quotaConfigHistory();
    updateLoading(false);
    if (errCode === 0) {
      updateInputValue(datas.quota);
      updateSelectValue(datas.quotaType);
    }
  };

  useEffect(() => {
    if (visible) {
      fetchHistory();
    }
  }, [visible]);

  const parserInputValue = value => {
    const temp = /\d+(\.\d+)?/.exec(value);
    let res = '';
    if (temp) {
      res = Math.floor(temp[0]);
    }
    if (res > 10000000) {
      res = 10000000;
      message.error('最大配额为10000000');
    }
    return res;
  };

  const onModalOk = async () => {
    if (!inputValue) {
      return message.error("请输入短信配额");
    }
    if (!selectValue) {
      return message.error("请选择短信配额类型");
    }
    const { errCode, errMsg } = await addQuotaConfig({
      quota: inputValue,
      quotaType: selectValue
    });
    if (errCode === 0) {
      message.success("设置成功");
      // 关闭modal
      onCancel();
    } else {
      message.error(errMsg);
    }
    return false;
  };
  return (
    <Modal
      title="短信配额配置"
      visible={visible}
      width={580}
      okText="提交"
      onCancel={onCancel}
      onOk={onModalOk}
    >
      <Spin spinning={loading}>
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "center"
          }}
        >
          <span className="starPrefix" />
          <span
            style={{
              marginRight: "8px"
            }}
          >
            默认短信配额：
          </span>
          <InputNumber
            value={inputValue}
            placeholder="请选择数字"
            style={{
              width: "116px",
              marginRight: "8px"
            }}
            min={0}
            max={10000000}
            parser={value => parserInputValue(value)}
            onChange={value => {
             updateInputValue(value);
            }}
          />
          <Select
            style={{
              width: "244px"
            }}
            value={selectValue}
            placeholder="请选择短信配额类型"
            onChange={val => {
              updateSelectValue(val);
            }}
          >
            <Select.Option value={1}>按年度</Select.Option>
            <Select.Option value={2}>按月份</Select.Option>
          </Select>
        </div>
      </Spin>
    </Modal>
  );
};

export default SMSconfigModal;
